<?php
//消费券及领取操作

namespace App\Repositories;

class BaseRepository
{
    /**
     * @param $model
     * @param $filter
     * @return mixed
     */
    public function buildQuery ($model, $filter) {
        $wheres = empty($filter['where']) ? null : $filter['where'];
        $whereBetween = empty($filter['whereBetween']) ? null : $filter['whereBetween'];
        if ($wheres) {
            foreach ($wheres as $where) {
                $w = end($where);
                $when = isset($w) && strlen(trim($w)) > 0;
                $model->when($when, function ($query) use ($where) {
                    $count = count($where);
                    if ($count == 2) {
                        $query->where($where[0], $where[1]);
                    } else {
                        $query->where($where[0], $where[1], $where[2]);
                    }
                });
            }
        }
        if ($whereBetween) {
            foreach ($whereBetween as $between) {
                $model->when(end($between), function ($query) use ($between) {
                    $query->whereBetween($between[0], $between[1]);
                });
            }
        }
        return $model;
    }

    /**
     * @param $params
     * @return array
     */
    protected function _getOrders($params)
    {
        $sort = [];
        foreach ($params as $key => $value) {
            if (str_contains($key, 'sort_')) {
                $sort[str_replace('sort_', '', $key)] = $value;
            }
        }
        return $sort;
    }

    /**
     * @param $model
     * @param $filter
     * @param int $pageSize
     * @param string[] $fields
     * @param string $pageName
     * @return array
     */
    public function getListItems ($model, $filter, $pageSize = 20, $fields = ['*'], $pageName = 'page', $orders = null) {
        $model = $this->buildQuery($model, $filter);
        if (is_array($orders)) {
            foreach ($orders as $field => $order) {
                if ($order) {
                    $model->orderBy($field, $order);
                }
            }
        }
        $paginator = $model->orderBy('id', 'desc')
            ->paginate($pageSize, $fields, $pageName);
        return [
            'list' => $paginator->items(),
            'current_page' => $paginator->currentPage(),
            'total' => $paginator->total(),
            'per_page' => $paginator->perPage(),
        ];
    }

    /**
     * 获取统计数据
     * @param $model
     * @param $filter
     * @return mixed
     */
    public function getStatisticsModel ($model, $filter) {
        $model = $this->buildQuery($model, $filter);
        return $model;
    }

    /**
     * 新增或修改
     * @param $params
     * @return mixed
     */
    public function saveOrUpdate ($model, $params)
    {
        $user = request()->user();
        $params['admin_id'] = $user['id'];
        $model = 'App\Models\\' . $model;
        $model = new $model;
        if (empty($params['id'])) {
            $addResult = $this->add($model, $params);
            return $addResult;
        } else {
            $updateResult = $this->update($model, $params);
            if ($updateResult) {
                return $params['id'];
            }
        }
         return false;
    }

    /**
     * @param $params
     * @return mixed
     */
    private function add ($model, $params) {
        $now = date('Y-m-d h:i:s');
        $saveData = $this->_getSaveData($params);
        $followId = $model->insertGetId($saveData);
        return $followId;
    }


    /**
     * @param $params
     * @return mixed
     */
    private function update ($model, $params) {
        $updateData = $this->_getSaveData($params);
        $rowsAffected = $model->where('id', $params['id'])
            ->where('admin_id', $params['admin_id'])
            ->update($updateData);
        return $rowsAffected;
    }

    /**
     * @param $params
     * @return array
     */
    protected function _getSaveData ($params) {
        $date = date('Y-m-d h:i:s');
        $data = [
            'created_at' => $date,
            'updated_at' => $date
        ];
        foreach ($params as $key => $param) {
            if (isset($param)) {
                $data[$key] = $param;
            }
        }
        return $data;
    }
}
